import axios from 'axios'
import router from '../router'
axios.defaults.timeout = 5000 // 超市时间是5秒
// axios.defaults.withCredentials = true // 允许跨域
// Content-Type 响应头
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
// 基础url
axios.defaults.baseURL = 'http://home.silvericekey.fun:32095'
// axios.defaults.baseURL = 'http://localhost:8888'

axios.interceptors.response.use(response => {
  console.log(response.headers.satoken)
  console.log('res.msg => ' + response.data.msg)
  if (response.data.msg === 'token已被顶下线') {
    alert('你已在别处登陆，如需要请重新登陆')
    localStorage.removeItem('SaToken')
    localStorage.removeItem('userName')
    router.replace({
      path: '/',
      query: {
        redirect: router.currentRoute.fullPath
      }
    })
  }
  localStorage.setItem('SaToken', response.headers.satoken)
  return response
},
error => {
  return Promise.reject(error)
})
axios.interceptors.request.use(request => {
  console.log('request => ' + request.data)
  request.headers['SaToken'] = localStorage.getItem('SaToken')
  return request
},
error => {
  return Promise.reject(error)
})
/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function get(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params
    })
      .then(response => {
        resolve(response.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, data)
      .then(response => {
        resolve(response.data)
      }, err => {
        reject(err)
      })
  })
}

/**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function patch(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.patch(url, data)
      .then(response => {
        resolve(response.data)
      }, err => {
        reject(err)
      })
  })
}

/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.put(url, data)
      .then(response => {
        resolve(response.data)
      }, err => {
        reject(err)
      })
  })
}
